package com.example.mall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mall.pojo.Rbody;
import com.example.mall.pojo.SystemUser;
import com.example.mall.pojo.User1;
import com.example.mall.pojo.UserIn;
import com.example.mall.service.SystemUserService;
import com.example.mall.utils.JwtUtils;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@CrossOrigin
@Slf4j
@AllArgsConstructor
public class LoginController {

    SystemUserService systemUserService;


    @PostMapping("/login")
    public Rbody loginUser(@RequestBody String body , HttpServletRequest request, HttpServletResponse response) throws Exception {

        System.out.println(body);
        User1 user1 = JSON.parseObject(body, User1.class);
        System.out.println(user1.getUsername());
        String loginPassword = DigestUtils.md5DigestAsHex(user1.getPassword().getBytes());
        Rbody rbody = new Rbody();
        SystemUser systemUser = systemUserService.loginSystemUser(user1.getUsername(),loginPassword);
        if(systemUser==null){
            rbody.getMeta().setStatus(400);
            rbody.getMeta().setMsg("登录失败");
        }else {
            rbody.getMeta().setStatus(200);
            rbody.getMeta().setMsg("登录成功");
            String token= JwtUtils.createToken(systemUser.getMg_id().toString(),systemUser.getMg_name());
            systemUser.setToken(token);
            HttpSession session = request.getSession();
            session.setAttribute("systemUser",systemUser.getMg_id().toString());
            System.out.println("***"+session);
//            request.setAttribute();
            rbody.setData(systemUser);
            System.out.println(rbody);
        }

        return rbody;



    }
}
